<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="900px"
      height="600px"
      destroy-on-close
      style="max-height: 800px"
      draggable
      @close="closeDialog"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="78px"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="班组编号" prop="teamCode" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.teamCode"
                placeholder="请输入班组编号"
                clearable
                disabled
              />

              <span v-else>{{ formData.teamCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="班组名称" prop="teamName" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.teamName"
                placeholder="请输入班组名称"
                clearable
                disabled
              />

              <span v-else>{{ formData.teamName }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h4 class="mb-[20px] mt-[20px]">班组成员</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增</el-button
          >
        </div>
        <div class="formTable">
          <el-table
            :data="formData.details"
            :key="Math.random"
            border
            max-height="250"
          >
            <el-table-column
              label="班组成员"
              props="memberName"
              align="center"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.memberList'"
                  label-width="0"
                  :rules="rules.memberRole"
                >
                  <SelectPerson-Member
                    :key="$index"
                    :isMultiple="false"
                    :maxCollapseTags="5"
                    :showSelectPerson="row.memberList"
                    @get-person="
                      (id, object) => getDayPerson(id, object, $index)
                    "
                    :width="'100%'"
                    :disabled="row.memberId != ''"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="成员角色"
              props="memberRole"
              min-width="150"
              align="center"
              style="padding-top: 15px"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.memberRole'"
                  :rules="rules.memberRole"
                  label-width="0"
                >
                  <el-select
                    v-model="row.memberRole"
                    placeholder="请选择成员角色"
                    clearable
                    style="width: 100%"
                    @change="(e) => handleChange(e, $index)"
                  >
                    <el-option
                      v-for="item in dictionaryStore.filterDictList(
                        'teamMembers'
                      )"
                      :key="item.value"
                      :label="item.label"
                      :value="Number(item.value)"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useDictionary } from "@/utils/useTable";

defineOptions({
  name: "EAMCREWMEMBEREDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  crewMembersData: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  teamCode: "",
  teamName: "",
  teamType: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  userDay: "",
  details: [
    {
      id: "",
      teamId: "",
      teamCode: "",
      memberId: "",
      memberName: "",
      memberRole: "",
      memberRoleName: "",
      deleted: "",
      enabled: 1,
      ids: [],
      organizationCode: "",
      organizationId: "",
      plantCode: "",
      plantId: "",
      remarks: "",
      version: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      memberList: [],
    },
  ],
  crewEquipments: [],
});

/** rules规则 */
const rules = reactive({
  memberRoleName: [
    {
      required: true,
      message: "请选择角色",
      trigger: "change",
    },
  ],
  memberRole: [
    {
      required: true,
      message: "请选择角色",
      trigger: "change",
    },
  ],
});

/** 删除行 */
const isValidated = ref(false);
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details: any = {
  id: "",
  teamId: "",
  teamCode: "",
  memberId: "",
  memberName: "",
  memberRole: "",
  memberRoleName: "",
  deleted: "",
  enabled: 1,
  ids: [],
  organizationCode: "",
  organizationId: "",
  plantCode: "",
  plantId: "",
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  memberList: [],
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      getDetails(newVal?.id);
    }
  }
);

// 获取成员table数据并赋值 班组成员
const getDetails = async (id) => {
  if (id) {
    await request({
      url: "eam/eamTeam/getDetails",
      method: "post",
      data: {
        id: id,
      },
    }).then((res) => {
      // 有id时 发请求获取人员数据并复制
      formData.details = res.data;
      // 遍历数据 给每个数据添加memberList属性 用于组件回显
      formData.details.forEach((element, index) => {
        element.memberList = [
          { id: element.memberId, personName: element.memberName },
        ];
      });
      console.log(res.data);
    });
  }
};
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
const crewMembers1: any = {
  id: "",
  crewId: "",
  teamCode: "",
  memberId: "",
  memberName: "",
  memberRole: "",
  memberRoleName: "",
  deleted: "",
  enabled: 1,
  ids: [],
  organizationCode: "",
  organizationId: "",
  plantCode: "",
  plantId: "",
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  memberList: [],
};
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formData.id = "";
  formData.teamCode = "";
  formData.teamName = "";
  formData.teamType = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.details = [crewMembers1];
}

const loading = ref(false);

/** 班制保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eamTeam/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}
// 获取选中的数据进行回显并赋值
const noRepeat = ref(true);
function getDayPerson(Ids: string[], Objects: any, index) {
  for (let i = 0; i < formData.details.length; i++) {
    if (formData.details[i].memberId == Objects[0].id) {
      ElMessage.error("该班组成员已存在，请重新选择");
      noRepeat.value = false;
      break;
    }
  }

  if (noRepeat.value == true) {
    formData.details[index].memberList = Objects.map((item: any) => {
      return { id: item.id, personName: item.personName };
    });
    formData.details[index].memberEmpNo = Objects[0].empNo;
    formData.details[index].memberId = Objects[0].id;
    formData.details[index].memberName = Objects[0].personName;
  } else {
    formData.details[index].memberList = [];
    noRepeat.value = true;
  }
}

// 点击角色下拉框 进行id赋值

const handleChange = (e, index) => {
  if (e) {
    formData.details[index].memberRoleName = useDictionary("teamMembers", e);
  } else {
    formData.details[index].memberRoleName = "";
  }
};
</script>
<style lang="scss" scoped>
.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-table .el-form-item) {
  padding: 9px 0 0 0 !important;
}
:deep(.el-table) {
  .el-table__body td.el-table__cell {
    padding: 0 !important;
  }
}
:deep(.el-table .el-form-item__error) {
  font-size: 11px !important;
}
</style>
